package com.neusoft.neuiotms.dcom.converter.report;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcom.dto.report.ReportToolDTO;
import com.neusoft.neuiotms.dcom.model.report.ReportTool;
import com.neusoft.neuiotms.dcom.model.report.ReportToolItem;
import com.neusoft.neuiotms.dcom.repository.report.ReportToolItemRepository;
import com.neusoft.neuiotms.dcom.repository.report.ReportToolRepository;

@Component
public class ReportToolConverter extends AbstractConverter<ReportTool, ReportToolDTO> {

    @Autowired
    private ReportToolRepository reportToolRepository;
    @Autowired
    private ReportToolItemConverter reportToolItemConverter;
    @Autowired
    private ReportToolItemRepository reportToolItemRepository;

    @Override
    public ReportTool toModel(final ReportToolDTO dto) {

        ReportTool model;

        if (dto.isNew()) {
            model = new ReportTool();
        } else {
            model = this.reportToolRepository.getOne(dto.getId());
        }

        model.setName(dto.getName());
        model.setCode(dto.getCode());
        model.setSelectSql(dto.getSelectSql());

        final List<ReportToolItem> items = model.getReportToolItem().stream().collect(Collectors.toList());

        items.forEach(k -> {
            model.getReportToolItem().remove(k);
            this.reportToolItemRepository.delete(k);
        });

        dto.getReportToolItem().stream().map(s -> {
            final ReportToolItem itemModel = this.reportToolItemConverter.toModel(s);
            itemModel.setReportTool(model);
            return itemModel;
        }).forEach(model.getReportToolItem()::add);

        return model;
    }

    @Override
    public ReportToolDTO toDTO(final ReportTool model, final boolean forListView) {

        final ReportToolDTO dto = new ReportToolDTO();

        dto.setId(model.getId());
        dto.setName(model.getName());
        dto.setCode(model.getCode());
        dto.setSelectSql(model.getSelectSql());

        model.getReportToolItem().stream().map(s -> this.reportToolItemConverter.toDTO(s)).filter(k -> null != k)
                .forEach(dto.getReportToolItem()::add);
        return dto;
    }

}
